package com.demo.utils;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * @author wangfengchen
 */
public class MoneyConvertUtil {

  /**
   * 元转换成分
   *
   * @param money
   * @return
   */
  public static String changeY2F(String money) {
    if (money == null || money.equalsIgnoreCase("0")) {
      return "";
    }
    // 金额转化为分为单位
    // 处理包含, ￥ 或者$的金额
    String currency = money.replaceAll("\\$|\\￥|\\,", "");
    int index = currency.indexOf(".");
    int length = currency.length();
    long amLong;
    if (index == -1) {
      amLong = Long.parseLong(currency + "00");
    } else if (length - index >= 3) {
      amLong = Long.parseLong(
          (currency.substring(0, index + 3)).replace(".", ""));
    } else if (length - index == 2) {
      amLong = Long.parseLong(
          (currency.substring(0, index + 2)).replace(".", "") + 0);
    } else {
      amLong = Long.parseLong(
          (currency.substring(0, index + 1)).replace(".", "") + "00");
    }
    return Long.toString(amLong);
  }

  /**
   * 分转元，转换为bigDecimal在toString
   *
   * @return
   */
  public static String changeF2Y(int price) {
    return new BigDecimal(price).divide(new BigDecimal(100), 2,
        RoundingMode.HALF_UP).toString();
  }

  public static void main(String[] args) {
    System.out.println(changeY2F(new BigDecimal("0.01").toString()));
    System.out.println(changeY2F(new BigDecimal("100").toString()));

    System.out.println(changeF2Y(1));
    System.out.println(changeF2Y(10));
  }
}
